//
//  CollectionViewController.m
//  Housekeeping
//
//  Created by 辰领科技 on 16/5/24.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "CollectionViewController.h"
#import "CollectionViewCell.h"
#import "HouseCleanViewController.h"

static NSString *cellIdentifier = @"CollectionViewCell";

@interface CollectionViewController ()
<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property(nonatomic,strong)NSMutableArray * collectsArray;

@end

@implementation CollectionViewController

- (void)viewWillAppear:(BOOL)animated{
    [self addRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO =  1;
    _collectsArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    UICollectionViewFlowLayout *FlowLayout =[[UICollectionViewFlowLayout alloc]init];
    FlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    FlowLayout.minimumInteritemSpacing = 0*VerticalRatio();
    FlowLayout.minimumLineSpacing = 0*VerticalRatio();
    self.collectionView.collectionViewLayout = FlowLayout;
    
    [self.collectionView registerNib:[UINib nibWithNibName:cellIdentifier bundle:nil] forCellWithReuseIdentifier:cellIdentifier];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.showsVerticalScrollIndicator = NO;
  
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.collectionView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getCollectssList];
        });
    }];
    // 马上进入刷新状态
    [self.collectionView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.collectsArray.count == _totle) {
        [self.collectionView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getCollectssList];
        });
    }

}


#pragma mark === 订单列表
- (void)getCollectssList{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:@"" forKey:@"mordStatus"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryMyCollectGoodList withHttpType:@"POST" withTag:HK_HK_queryMyCollectGoodList];
    
    
}


#pragma mark - <UICollectionViewDelegate && UICollectionViewDataSource && UICollectionViewDelegateFlowLayout>
//定义 UICollectionView 的 cell 个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _collectsArray.count;
}

//定义UICollectionView Cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(159*VerticalRatio(), 140*VerticalRatio());
}

//定义 UICollectionView 的边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}


//定义 UICollectionView cell 展示的内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    NSDictionary * dic = _collectsArray[indexPath.row][@"mallGoods"];
    NSString * image = [NSString stringWithFormat:@"%@",dic[@"mgooImage"]];
    if (image.length>0) {
        [cell.collectImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }
    cell.collectName.text =[NSString stringWithFormat:@"%@", dic[@"mgooName"]];
    NSString * price =[NSString stringWithFormat:@"%@",dic[@"mgooSalePrice"]];
    NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString: [NSString stringWithFormat:@"价格:￥%@/m²     %@元起",_collectsArray[indexPath.row][@"mcgoMcgoPrice"],price]];
//    [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.976 blue:0.702 alpha:1.000] range:NSMakeRange(str.length - price.length-2, str.length+2)];
    cell.collectPrice.attributedText = str;
    cell.collectBuyTimes.text = [NSString stringWithFormat:@"%@人购买",dic[@"mgooSaleNum"]];


    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    HouseCleanViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"HouseClean"];
    page.goodsId = [NSString stringWithFormat:@"%@",_collectsArray[indexPath.row][@"mcgoId"]];
    [[Common getNavigation]pushViewController:page];
}


#pragma mark - 退出
- (IBAction)Back:(id)sender {
    [self backBtn];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_collectionView.header endRefreshing];
    [_collectionView.footer endRefreshing];
    if (tag==HK_HK_queryMyCollectGoodList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            _totle = [database[@"result"][@"totalResults"] integerValue];
                            if (_totle > PageSize) {
                                __weak __typeof(self) weakSelf = self;
                                if (!self.collectionView.footer) {
                                    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                                    self.collectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                                        [weakSelf loadMoreData];
                                    }];
                                }
                            }
                            if (self.pageNO == 1) {
                                [self.collectsArray removeAllObjects];
                            }
            NSArray *arr = database[@"result"][@"rows"];
            for (id entity in arr) {
                [self.collectsArray addObject:entity];
            }
            _collectionView.dataSource = self;
            _collectionView.delegate = self;
            [_collectionView reloadData];
            
                        });
            
            
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
